import {View} from '@tarojs/components'
import React, { useState, useEffect } from 'react';
import { useDidHide } from '@tarojs/taro';
import './count-down.scss'
import {calcTime} from '../../utils/tools'

const CountDown1: React.FC<{ time: number | string; type?: 'end' | 'start' | string; style?: string }> = (props) => {
  const [timeInfo, setTimeInfo] = useState({
    dur: 0,
    day: '00',
    hour: '00',
    minute: '00',
    second: '00',
    month: '00',
    year: '00',
  })
  const [frist, setFrist] = useState(true)
  let timer: any;
  useEffect(() => {
    let nowTime = new Date().getTime()
    let timeNumer = 0;
    if (typeof props.time === 'string') {
      timeNumer = new Date(props.time).getTime()
    } else {
      timeNumer = props.time
    }
    if (frist) {
      const times = calcTime(timeNumer, nowTime)
      setTimeInfo(times)
      setFrist(false)
    }
    timer = setInterval(() => {
      const times = calcTime(timeNumer, nowTime)
      if (times.dur <= 0) {
        clearInterval(timer)
      }
      setTimeInfo(times)
      nowTime = nowTime + 1000
    }, 1000)
    return () => {
      clearInterval(timer)
    }
  }, [props.time])
  useDidHide(() => {
    clearInterval(timer)
  })
  return (
    <View className='countDown-1' style={props.style}>
      <View className='tips'>距{props.type === 'start' ? '开始' : '结束'}还有：</View>
      {timeInfo.day != '00' && <View className='timer-item number'>{timeInfo.day}</View>}
      {timeInfo.day != '00' && <View className='timer-item text'>天</View>}
      <View className='timer-item number'>{timeInfo.hour}</View>
      <View className='timer-item text'>时</View>
      <View className='timer-item number'>{timeInfo.minute}</View>
      <View className='timer-item text'>分</View>
      <View className='timer-item number'>{timeInfo.second}</View>
      <View className='timer-item text'>秒</View>
    </View>
  )
}

CountDown1.defaultProps = {
  time: 0,
  type: 'start',
  style: ''
}

export default CountDown1
